package com.kedacom.freedomLabel.viewmodel;


import android.support.annotation.Nullable;

import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.base.BaseViewModel;
import com.kedacom.freedomLabel.base.UserCache;
import com.kedacom.freedomLabel.model.bean.Config;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.model.db.DataCallback;
import com.kedacom.freedomLabel.model.db.DataLoader;
import com.kedacom.freedomLabel.model.db.dao.ConfigDao;
import com.kedacom.freedomLabel.utils.log.LLog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInformationViewModel extends BaseViewModel {

    public void saveUserInformation(List<Config> configList) {
        if (configList == null || configList.isEmpty()) return;
        ConfigDao dao = AppDatabase.getInstance().configDao();
        DataLoader.save(dao, configList, new DataCallback<List<Config>>() {
            @Override
            public void success(@Nullable List<Config> data) {
                if (data != null) {
                    Map<String, String> map = new HashMap<>();
                    for (Config bean : data) {
                        map.put(bean.configKey, bean.configValue);
                    }
                    UserCache.init(map);
                    // 更新UI显示
                    sendEmptyMessage(Options.MSG_USER_INFORMATION);
                }
            }

            @Override
            public void error(@Nullable String errorMessage) {
                showToast("用户信息读取失败", TOAST_ERROR);
                LLog.debug("用户信息读取失败 " + errorMessage);
            }
        });
    }
}